package com.gdit.zax.servletjsp;

import java.io.IOException;
import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdit.zax.Constant;
import com.gdit.zax.dao.GroupDao;
import com.gdit.zax.dao.PlanDao;
import com.gdit.zax.dao.UserDao;
import com.gdit.zax.entitys.Course;
import com.gdit.zax.entitys.GroupAll;
import com.gdit.zax.entitys.Plan;
import com.gdit.zax.entitys.UserInfo;
import com.gdit.zax.factory.DAOFactory;
import com.gdit.zax.utils.DBUtil;
import com.gdit.zax.utils.Repost;
import com.gdit.zax.utils.webUtil;

public class GiveHomeWork extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 变量准备
		String token = webUtil.getCookie(request, "LoginCookie");
		String cname = request.getParameter("coursename");
		String name = request.getParameter("name");
		String content = request.getParameter("content");
		
		// 数据库，权限检测
		Connection conn = DBUtil.getConnection();
		if (conn == null) {
			Repost.dberror(request, response);
			return;
		}

		DAOFactory dao = DAOFactory.init(conn, request, response);
		UserDao udao = dao.getUserDao();
		UserInfo uinfo = udao.getInfo(Constant.LOGINTYPE_WEB, token);
		if (uinfo == null) {
			Repost.nologin(response);
			return;
		}
		if (uinfo.getUlevel() < Constant.ULEVEL_teacher) {
			Repost.message("你还没有权限!", request, response);
			return;
		}

		//判断课程是否存在
		Course course = dao.getCourseDao().getCourseByName(cname);
		if (course==null) {
			Repost.message("该课程不存在或被删除!", request, response);
			return;
		}
		
		// 开始
		GroupDao gdao =dao.getGroupDao();
		List<GroupAll> list = gdao.listGroupSub(uinfo.getId(), 1, 1000);
		PlanDao pdao = dao.getPlanDao();
		int count = list.size();
		int successcount = 0;
		for (GroupAll student:list) {
			Plan pla = new Plan();
			pla.setUserid(student.getT_user_id());
			pla.setContent(content);
			pla.setName(name);
			pla.setOverseer(uinfo.getNick());
			pla.setType(1);
			pla.setCouresid(course.getId());
			pla.setPlantime(System.currentTimeMillis() + 1000*60*60*24*365);//1年有效
			if (pdao.addPlan(pla)){
				successcount++;
			}
		}
		Repost.message("布置作业成功!共有学生" + count + "人，布置成功:" + successcount + "人!", request, response);

	}

}
